import axios from 'axios'
import qs from 'qs'
import Vue from 'vue'

axios.defaults.baseURL = 'http://192.168.168.38:8070';
axios.defaults.withCredentials = true;//跨域
axios.interceptors.response.use(function (response) {// 添加响应拦截器
    console.log(response.data.code);

    if (response.data.code == -302) {
        Vue.prototype.$notify_err(response.data.msg);
         window.location.href = window.location.protocol + "//" + window.location.host + "/#/login";
        localStorage.setItem('isLogOut', 'true');
        setTimeout(function () {
            window.location.href = window.location.protocol + "//" + window.location.host + "/#/login";
        }, 3000);
        return;
    }
    return response;
}, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
});

axios.interceptors.request.use(function (config) {
    return config;
}, function (error) {
    // Do something with request error
    return Promise.reject(error);
});

/**
 *定义了一个ajax对象，赋予Vue的prototype属性两个方法
 */
 const ajax = {};
 ajax.install = (Vue, options) => {
    Vue.prototype.get = (url, params, isneed, loadstr, fun) => {
        if (isneed) {
         var loadingInstance =  Vue.prototype.$loading({ fullscreen: true });
     }
     axios.get(url, {params: params}).then((res) => {
        loadingInstance.close();
        if (res.data) {
            if (fun) {
                fun(res.data)
            }
        } else {
            Vue.prototype.$notify_err(res.data.msg);
        }
    }).catch((error) => {
        loadingInstance.close();
    });
    };//Vue.prototype之所以能取到是因为在main.js中Vue.use(VueToast);
    //post
    Vue.prototype.post = (url, params, isneed, loadstr, fun, isBody) => {
        if (isneed) {
            var loadingInstance =  Vue.prototype.$loading({ fullscreen: true });
        }
        axios.post(url, isBody ? qs.stringify(params) : params, {
            headers: {
                'Content-Type': isBody ? 'application/x-www-form-urlencoded' : 'application/json'
            },
        }).then((res) => {
            loadingInstance.close();
            if (res.data.code == 200) {
                if (fun) {
                    fun(res.data)
                }
            } else {
                Vue.prototype.$notify_err(res.data.msg);
            }
        }).catch((error) => {
            loadingInstance.close();
        });
    }
};
export default ajax;
